package com.sgb.kjwl.view.ui.activity.manage;

import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.androidkun.xtablayout.XTabLayout;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivitySpecialQualificationBinding;
import com.sgb.kjwl.di.manage.DaggerEnterpriseManageComponent;
import com.sgb.kjwl.di.manage.EnterpriseManageModule;
import com.sgb.kjwl.model.entity.ParentAreaEntity;
import com.swgk.core.util.PickSelectEntity;
import com.sgb.kjwl.model.entity.enterprise.IpPickSelectEntity;
import com.sgb.kjwl.model.entity.manage.SpecialQualificationEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.view.ui.adapter.manage.SpecialQualificationAdapter1;
import com.sgb.kjwl.view.widget.ActionBar;
import com.sgb.kjwl.view.widget.EnterprisePopWindow;
import com.sgb.kjwl.view.widget.IpPopWindow;
import com.sgb.kjwl.view.widget.PickTwoLevelPopChangeWindow;
import com.sgb.kjwl.view.widget.ThreeLevelAreaWindow;
import com.sgb.kjwl.viewmodel.manage.SpecialQualificationModel1;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.helper.OnMultiClickListener;
import com.swgk.core.recyclerview.entity.BaseAreaEntity;
import com.swgk.core.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

//专项资质  *ChenT
public class SpecialQualificationActivity extends AppActivity {

    @Inject
    SpecialQualificationModel1 specialQualificationModel1;
    ActivitySpecialQualificationBinding binding;
    SpecialQualificationAdapter1 adapter1;
    private PickTwoLevelPopChangeWindow specialTypeWindow;//资质类型
    private EnterprisePopWindow departmentTypeWindow;//资质类型
    private ThreeLevelAreaWindow iprAreaPopWindow;//省市弹窗
    private Map<String, Object> map = new HashMap<>();
    private boolean isChange1 = false, isChange3 = false, isChange4 = false;
    String mAreaCode = "";
    String mCityNo = "";
    String name1 = "";
    private IpPopWindow homeGoodsSelectionTypePopWindow;
    private List<PickSelectEntity<List<PickSelectEntity>>> list;
    private List<ParentAreaEntity<List<ParentAreaEntity>>> departmentList;//备案单位

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerEnterpriseManageComponent.builder().appComponent(appComponent)
                .enterpriseManageModule(new EnterpriseManageModule(this))
                .build()
                .inject(this);
    }

    public static void startAction(Context context) {
        Intent intent = new Intent(context, SpecialQualificationActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActionBar.setMenuFunctionClick(new OnMultiClickListener() {
            @Override
            public void onMultiClick(View v) {
                map.put("name", mActionBar.getEditText());
                specialQualificationModel1.findMyListByCompanyInfoNo(map, false);
            }
        });

        mActionBar.setClearEdiText(new ActionBar.ClearEdiText() {
            @Override
            public void clearEdiText() {
                map.put("name", "");
                specialQualificationModel1.findMyListByCompanyInfoNo(map, false);
            }

            @Override
            public void search() {
                closeKeybord();
                map.put("name", mActionBar.getEditText());
                specialQualificationModel1.findMyListByCompanyInfoNo(map, false);
            }
        });
    }

    @Override
    protected void initView() {
        super.initView();
        binding = DataBindingUtil.setContentView(this, R.layout.activity_special_qualification);

        homeGoodsSelectionTypePopWindow = new IpPopWindow(getActivity());
        homeGoodsSelectionTypePopWindow.setDefItem(0);
        homeGoodsSelectionTypePopWindow.setBgView(binding.grayLayout);

        homeGoodsSelectionTypePopWindow.setOnResultClick((key1, key2, key3) -> {
            binding.tlCompanyTrades.getTabAt(((int) key2)).select();
            binding.editView.setImageResource(R.mipmap.btn_expand1);
        });
        homeGoodsSelectionTypePopWindow.setOnDismissListener(() -> binding.editView.setImageResource(R.mipmap.btn_expand1));

        specialQualificationModel1.queryIndustryCategry(false);
        binding.tvType.setOnClickListener(this);
        binding.tvArea.setOnClickListener(this);
        binding.tvDepartment.setOnClickListener(this);
        binding.editView.setOnClickListener(this);
        adapter1 = new SpecialQualificationAdapter1(this, null);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        binding.recyclerView.setLayoutManager(layoutManager);
        binding.recyclerView.setLoadingMoreEnabled(true);
        binding.recyclerView.setAdapter(adapter1);
        specialQualificationModel1.findMyListByCompanyInfoNo(map, false);
        binding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                specialQualificationModel1.findMyListByCompanyInfoNo(map, false);
            }

            @Override
            public void onLoadMore() {
                specialQualificationModel1.findMyListByCompanyInfoNo(map, true);
            }
        });

        specialTypeWindow = new PickTwoLevelPopChangeWindow(getActivity());
        specialTypeWindow.setBgView(binding.grayLayout);
        specialTypeWindow.setFocusable(false);
        specialTypeWindow.setOutsideTouchable(true);
        specialTypeWindow.setOnResultClick((key1, key2, key3) -> {
            String qualificationClassNo = ((ParentAreaEntity) key1).getNo();
            String className = ((ParentAreaEntity) key2).getNo();
            map.put("qualificationClassNo", qualificationClassNo);
            map.put("className", className);
            specialQualificationModel1.findMyListByCompanyInfoNo(map, false);

            String name = ((ParentAreaEntity) key1).getName();
            if (!name.equals("不限") || !key3.equals("不限")) {
                isChange1 = true;
                setTextViewBg(binding.tvType, R.drawable.search_new_blue_bg, R.mipmap.icon_down_red, R.color.color_main);
            } else {
                isChange1 = false;
                setTextViewBg(binding.tvType, R.drawable.search_bg, R.mipmap.ic_down_arrow_n, R.color.color_333333);
            }
        });
        specialTypeWindow.setOnCloseBack(() -> {
            if (!isChange1) {
                setTextViewBg(binding.tvType, R.drawable.search_bg, R.mipmap.ic_down_arrow_n, R.color.color_333333);
            }
        });
        departmentTypeWindow = new EnterprisePopWindow(getActivity());
        departmentTypeWindow.setFocusable(false);
        departmentTypeWindow.setOutsideTouchable(true);
        departmentTypeWindow.setBgView(binding.grayLayout);
        departmentTypeWindow.setOnResultClick((type, key2, key3) -> {
            String recordUnitNo = (String) type;
            map.put("recordUnitNo", recordUnitNo);
            specialQualificationModel1.findMyListByCompanyInfoNo(map, false);

            String name = (String) key2;
            if (!name.equals("不限")) {
                isChange4 = true;
                setTextViewBg(binding.tvDepartment, R.drawable.search_new_blue_bg, R.mipmap.icon_down_red, R.color.color_main);
            } else {
                isChange4 = false;
                setTextViewBg(binding.tvDepartment, R.drawable.search_bg, R.mipmap.ic_down_arrow_n, R.color.color_tab_one);
            }
        });
        departmentTypeWindow.setOnDismissListener(() -> {
            if (!isChange4) {
                setTextViewBg(binding.tvDepartment, R.drawable.search_bg, R.mipmap.ic_down_arrow_n, R.color.color_tab_one);
            }
        });

        iprAreaPopWindow = new ThreeLevelAreaWindow(getActivity()){
            @Override
            protected void provinceClick(BaseAreaEntity baseAreaEntity, int position) {
                super.provinceClick(baseAreaEntity, position);
                name1 = baseAreaEntity.getSimpleName();
                if (!mAreaCode.equals(baseAreaEntity.getId())){
                    mCityNo = "";
                    map.put("areaNo", mCityNo);
                }

                name1 = baseAreaEntity.getSimpleName();
                mAreaCode = baseAreaEntity.getId();

                map.put("provinceNo", mAreaCode);
            }

            @Override
            protected void cityClick(BaseAreaEntity baseAreaEntity, int position) {
                super.cityClick(baseAreaEntity, position);
                mCityNo = baseAreaEntity.getId();

                name1 = baseAreaEntity.getSimpleName();
                map.put("areaNo", mCityNo);
            }

            @Override
            protected void reset() {
                super.reset();
                iprAreaPopWindow.dismiss();
                specialQualificationModel1.findMyListByCompanyInfoNo(map, false);
            }
        };
        iprAreaPopWindow.setBgView(binding.grayLayout);
        iprAreaPopWindow.setThreeListIsGone(true);
        iprAreaPopWindow.setProvinceSingle();
        iprAreaPopWindow.setCitySingle();
        iprAreaPopWindow.setOnResultClick((key1, key2, key3) -> specialQualificationModel1.findMyListByCompanyInfoNo(map, false));
        iprAreaPopWindow.setOnDisMissClick(() -> {
            if (name1.equals("不限")||name1.equals("")) {
                binding.tvDepartment.setVisibility(View.GONE);
                isChange3 = false;
                binding.tvArea.contentSelect(false,false);
            } else {
                isChange3 = true;
                binding.tvDepartment.setVisibility(View.VISIBLE);
                binding.tvArea.contentSelect(true,false);
            }

            if (!isChange3) {
                binding.tvArea.contentSelect(false,false);
            }
        });
        specialQualificationModel1.getCityData();
        specialQualificationModel1.getDepartment();

        binding.tlCompanyTrades.addOnTabSelectedListener(new XTabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(XTabLayout.Tab tab) {
                int position = tab.getPosition();
                if (homeGoodsSelectionTypePopWindow == null) {
                    homeGoodsSelectionTypePopWindow = new IpPopWindow(SpecialQualificationActivity.this);
                }
                homeGoodsSelectionTypePopWindow.setDefItem(tab.getPosition());
                map.put("code", list.get(position).getNo());
                specialQualificationModel1.findMyListByCompanyInfoNo(map, false);
            }

            @Override
            public void onTabUnselected(XTabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(XTabLayout.Tab tab) {

            }
        });
    }

    @Override
    public void onMultiClick(View v) {
        super.onMultiClick(v);
        switch (v.getId()) {
            case R.id.right_view:
            case R.id.tv_cancel:
                break;
            case R.id.tv_type:
                setTextViewBg(binding.tvType, R.drawable.search_bg, R.mipmap.icon_up_red, R.color.color_main);
                specialQualificationModel1.findMyListByCompanyInfoNo();
                break;
            case R.id.tv_area:
                binding.tvArea.contentSelect(false,true);
                showProvincePopWindow();
                break;
            case R.id.tv_department:
                setTextViewBg(binding.tvDepartment, R.drawable.search_bg, R.mipmap.icon_up_red, R.color.color_main);
                if (departmentList != null && departmentList.size() > 0) {
                    showDepartment(this.departmentList);
                }
                break;
            case R.id.edit_view:
                specialQualificationModel1.queryIndustryCategry(true);
                binding.editView.setImageResource(R.mipmap.btn_expand_up_gray);
                break;
        }
    }

    public void setCityData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> datas, String areaCode) {
        iprAreaPopWindow.setDataForCompany(datas, true);
    }

    public void showSpecialTypeWindow(List<ParentAreaEntity<List<ParentAreaEntity>>> datas) {
        specialTypeWindow.setData(datas, false);
        specialTypeWindow.showPopwindow(binding.roomLayout, 0, 0);
    }

    private void showProvincePopWindow() {
        iprAreaPopWindow.showPopwindow(binding.roomLayout, 0, 0);
    }

    public void showList(List<SpecialQualificationEntity> list, boolean isLoadMore) {
        binding.recyclerView.refreshComplete();
        if (isLoadMore) {
            if (list.size() > 0) {
                binding.recyclerView.loadMoreComplete();
                adapter1.addDatas(list);
            } else {
                binding.recyclerView.setNoMore(true);
            }
            binding.recyclerView.setVisibility(View.VISIBLE);
        } else {
            if (list.size() > 0) {
                binding.recyclerView.setVisibility(View.VISIBLE);
                binding.empty.setVisibility(View.GONE);
                adapter1.setDatas(list);
                binding.recyclerView.setLoadingMoreEnabled(true);
            } else {
                adapter1.setDatas(null);
                binding.recyclerView.setVisibility(View.GONE);
                binding.empty.setVisibility(View.VISIBLE);
            }
        }
    }

    private void setDrwImage(TextView tv, int type) {
        Drawable img_off;
        Resources res = getResources();
        if (type == 0) {
            img_off = res.getDrawable(R.mipmap.icon_up_red);
        } else if (type == 1) {
            img_off = res.getDrawable(R.mipmap.icon_down_red);
        } else {
            img_off = res.getDrawable(R.mipmap.ic_down_arrow_n);
        }
        img_off.setBounds(0, 0, img_off.getMinimumWidth(), img_off.getMinimumHeight());
        tv.setCompoundDrawables(null, null, img_off, null); //设置右图标
    }

    private void setTextViewBg(TextView textView, int bg, int img, int textColor) {
        textView.setBackground(getResources().getDrawable(bg));
        Drawable drawable_n = getResources().getDrawable(img);
        drawable_n.setBounds(0, 0, drawable_n.getMinimumWidth(), drawable_n.getMinimumHeight());
        textView.setCompoundDrawables(null, null, drawable_n, null);
        textView.setTextColor(getResources().getColor(textColor));
    }

    public void tabData(List<PickSelectEntity<List<PickSelectEntity>>> list, boolean isList) {
        this.list = list;
        if (!isList) {
            for (PickSelectEntity oneDatum : list) {
                binding.tlCompanyTrades.addTab(binding.tlCompanyTrades.newTab().setText(oneDatum.getProjectscale()));
            }
        } else {
            List<IpPickSelectEntity> list1 = new ArrayList<>();
            for (PickSelectEntity<List<PickSelectEntity>> listPickSelectEntity : list) {
                list1.add(new IpPickSelectEntity(listPickSelectEntity.getNo(), listPickSelectEntity.getProjectscale(), "", "", "", "", ""));
            }
            homeGoodsSelectionTypePopWindow.showPopwindow(binding.tvTag, 0, 0);
            homeGoodsSelectionTypePopWindow.setData(list1);
        }
    }

    public void setDepartmentList(List<ParentAreaEntity<List<ParentAreaEntity>>> data) {
        this.departmentList = new ArrayList<>();
        this.departmentList.clear();
        this.departmentList = data;
    }

    public void showDepartment(List<ParentAreaEntity<List<ParentAreaEntity>>> data) {
        for (ParentAreaEntity entity : data) {
            if (!mAreaCode.isEmpty() && entity.getNo().equals(mAreaCode)) {
                List<PickSelectEntity> list = new ArrayList<>();
                List<ParentAreaEntity> parentAreaEntityList = (List<ParentAreaEntity>) entity.getChildren();
                for (ParentAreaEntity oneDatum : parentAreaEntityList) {
                    PickSelectEntity entity2 = new PickSelectEntity(oneDatum.getNo(), oneDatum.getName());
                    list.add(entity2);
                }
                list.add(0, new PickSelectEntity("", "不限"));
                departmentTypeWindow.setData(list);
                departmentTypeWindow.showPopwindow(binding.roomLayout, 0, 0);
                return;
            }
        }
    }
}
